<template>
  <div class="app-container">
    <el-form :inline="true" label-width="68px">
      <el-form-item label="商品名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:food:add']">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="foodList">
      <el-table-column label="商品编号" align="center" prop="foodId" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:food:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:food:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" top="15px">
      <header class="form_header">选择商品分类</header>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="category_select">
          <el-form-item  label="商品分类"  prop="typeId">
            <el-select v-model="form.typeId" filterable clearable  placeholder="请选择">
              <el-option
                v-for="type in typeOptions"
                :key="type.typeId"
                :label="type.name"
                :value="type.typeId"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-if="showAddType" class="add_category">
          <el-form-item label="商品分类" >
            <el-input v-model="form.typeName" placeholder="请输入商品分类名称" />
          </el-form-item>
          <el-form-item label="分类描述" >
            <el-input v-model="form.typeDescription" placeholder="请输入商品分类描述" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitType">提交</el-button>
          </el-form-item>
        </div>
        <div class="add_category_button" @click="addTypeFun">
          <i class="el-icon-caret-top edit_icon" v-if="showAddType"></i>
          <i class="el-icon-caret-bottom edit_icon" v-else slot="icon"></i>
          <span>添加商品分类</span>
        </div>
        <header class="form_header">商品信息</header>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品活动" prop="activity">
          <el-input v-model="form.activity" placeholder="请输入商品活动" />
        </el-form-item>
        <el-form-item label="商品详情" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入商品详情" />
        </el-form-item>
        <el-form-item label="商品特点" prop="status">
          <el-select v-model="form.attr"  placeholder="请选择">
            <el-option
              v-for="type in attrOptions"
              :key="type.dictValue"
              :label="type.dictLabel"
              :value="type.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="form.status"  placeholder="请选择">
            <el-option
              v-for="type in statusOptions"
              :key="type.dictValue"
              :label="type.dictLabel"
              :value="type.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片介绍">
          <el-upload
            :headers="headers"
            :action="uploadImgUrl"
            :limit="1"
            list-type="picture-card"
            :on-success="onSuccess	"
            :file-list="form.fileList"
            :auto-upload="true">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
        <el-row  style="overflow: auto; text-align: center;">
          <el-button type="primary" @click="dialogFormVisible = true" style="margin-bottom: 10px;">添加规格</el-button>
          <el-table
            :data="form.specfoods"
            style="margin-bottom: 20px;">
            <el-table-column
              prop="name"
              label="规格">
            </el-table-column>
            <el-table-column
              prop="packing"
              label="包装费">
            </el-table-column>
            <el-table-column
              prop="price"
              label="价格">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDeleteSpecs(scope.$index)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加规格" :visible.sync="dialogFormVisible">
      <el-form :inline="true"  :model="form.specsForm">
        <el-form-item label="规格">
          <el-input v-model="form.specsForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="包装费" >
          <el-input-number v-model="form.specsForm.packing" :min="0" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="form.specsForm.price" :min="0" :max="10000"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addspecs">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { listFood, getFood, delFood, addFood,addType, updateFood,listFoodType } from "@/api/system/food";
import IconSelect from "../../../components/IconSelect/index";
import { getToken } from '@/utils/auth'

export default {
  components: {IconSelect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      foodList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 商品类别
      typeOptions: [],
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      dialogImageUrl: '',
      dialogVisible: false,
      attrOptions:[],
      // 状态数据字典
      statusOptions: [],
      disabled: false,
      showAddType:false,
      dialogFormVisible:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        specsForm:{}
      },
      // 表单校验
      rules: {
        typeId: [
          { required: true, message: "商品分类必选", trigger: "blur" }
        ],
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_food_attr").then(response => {
      this.attrOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listFood(this.queryParams).then(response => {
        this.foodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleDeleteSpecs(index) {
      this.form.specfoods.splice(index, 1)
    },
    addTypeFun() {
      this.showAddType = !this.showAddType
    },
    addspecs() {
      this.form.specfoods.push({ ...this.form.specsForm })
      this.form.specsForm.name = ''
      this.form.specsForm.packing = 0
      this.form.specsForm.price = 20
      this.dialogFormVisible = false
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file) {
      this.form.fileList.forEach((item, i) => {
        if(item.url===file.url) {
          this.form.fileList.splice(i, 1)
        }
      })
    },
    onSuccess(response, file, fileList){
      this.form.fileList=fileList;
    },
    initImg() {
      if(this.form.fileList){
        this.form.fileList.forEach((item, i) => {
          if(item.response&&item.response.url) {
            item.url=item.response.url;
          }
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        foodId: undefined,
        typeId:undefined,
        typeName:undefined,
        typeDescription:undefined,
        iconName: undefined,
        name: undefined,
        activity: undefined,
        rankingWeight: undefined,
        description: undefined,
        attr: undefined,
        fileList: [],
        foodSpecs: 'one',
        specsForm: {
          name: '',
          packing: 0,
          price: 20
        },
        specfoods: [{
          name: '默认',
          packing: 0,
          price: 20
        }],
        remark: undefined
      };
      this.showAddType=false,
      this.dialogFormVisible=false,
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getTypeOptions(){
      listFoodType().then(response => {
        this.typeOptions = response.data;
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTypeOptions();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTypeOptions();
      getFood(row.foodId).then(response => {
        this.form = response.data;
        this.form.specsForm= {
          name: '',
          packing: 0,
          price: 20
        },
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.initImg();
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.foodId != undefined) {
            updateFood(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addFood(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },

    /** 提交分类 */
    submitType: function() {
      addType(this.form).then(response => {
        if (response.code === 200) {
          this.msgSuccess("新增分类成功");
          this.typeOptions=response.data;
          this.form.typeName=undefined;
          this.form.typeDescription=undefined;
        } else {
          this.msgError(response.msg);
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除属性名称为"' + row.name + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFood(row.foodId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    }
  }
};
</script>
<style>
  .form_header {
    text-align: center;
    margin-bottom: 10px;
    margin-top: 10px;
    font-weight:900;
  }
  .add_category_button {
    text-align: center;
    line-height: 40px;
    border-bottom-right-radius: 6px;
    border-bottom-left-radius: 6px;
    border: 1px solid #eaeefb;
    border-top: none;
    transition: all 400ms;
  }
  .add_category {
    background: #f9fafc;
    padding: 10px 30px 0px 10px;
    border: 1px solid #eaeefb;
    border-top: none;
  }
  .category_select {
    border: 1px solid #eaeefb;
    padding: 18px 0px 0px 0px;
    border-top-right-radius: 6px;
    border-top-left-radius: 6px;
  }
  .add_category_row {
    height: 0;
    overflow: hidden;
    transition: all 400ms;
    background: #f9fafc;
  }
</style>
